package com.wenx.concurrent.thread;

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;

/**
 * cyclicbarrier使用案例
 */
public class UseCyclicBarrier {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5,new CollectThread());

    //存放子线程运行结果容器
    private static ConcurrentHashMap<String,Long> resultMap = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new SubThread());
            thread.start();
        }
    }

    //到达屏障后执行
    private static class CollectThread implements Runnable{

        @Override
        public void run() {
            StringBuilder result = new StringBuilder();
            resultMap.forEach((k,v) -> result.append("[").append(v).append("]"));
            System.out.println("the result = " + result);
            System.out.println("do other business......");
        }
    }

    private static class SubThread implements Runnable{

        @Override
        public void run() {
            long id = Thread.currentThread().getId();
            resultMap.put(Thread.currentThread().getName(),id);
            Random random = new Random();
            try{
                if (random.nextBoolean()) {
                    Thread.sleep(2000+id);
                    System.out.println("Thread_"+id+"......do something");
                }
                System.out.println("Thread_"+id+" is awaiting");
                //等待
                cyclicBarrier.await();

                //到达屏障后执行
                //Thread.sleep(1000+id);
                System.out.println("Thread_"+id+"......do its something");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
